/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scserver03;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author laoxu
 */
public class SendScreenImage extends Thread{
    private Robot robot ;
    private DataOutputStream dos;
    public SendScreenImage(DataOutputStream dos){
        this.dos = dos;
    }
    //得到屏幕当前的显示画面并转换成byte数组
    private byte[] createImage(Rectangle rec) throws IOException {
		BufferedImage bufImage = robot.createScreenCapture(rec);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
		encoder.encode(bufImage);
		return baos.toByteArray();
	}
    public void run() {
        try {
            robot = new Robot();
//            System.out.println("robot");
        } catch (AWTException ex) {
            Logger.getLogger(SendScreenImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        final Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
        final Dimension dm = tk.getScreenSize();//得到屏幕的大小
        final Rectangle rec = new Rectangle(dm);//得到屏幕当的显示
//        System.out.println(rec.x);
        try {
            dos.writeDouble(dm.getWidth());//向客户端发送屏幕宽度
            dos.writeDouble(dm.getHeight());//向客户端发送屏幕高度
            dos.flush();//刷新输入出缓冲区 确保数据发送完成
        } catch (IOException ex) {
            Logger.getLogger(SendScreenImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        int i = 0;
        while (true) {
            try {
                byte[] imgData = createImage(rec);// 将屏幕的画面转换成一个byte数组
//                File file = new File("f:\\image\\"+i+".jpg");
//                FileOutputStream fos = new FileOutputStream(file);
//                fos.write(imgData, 0, imgData.length);
//                i++;
//                System.out.println("发送");
                dos.writeInt(imgData.length);//向客户端发送画面数据的长度
                dos.write(imgData);//向客户端发送画面数据
                dos.flush();//刷新输出缓冲区 确保数据发送完成
                try {
                    Thread.sleep(30);//让线程休眠一段时间 能面截屏过快
                } catch (InterruptedException ex) {
                    Logger.getLogger(SendScreenImage.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex) {
                Logger.getLogger(SendScreenImage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
}
